<template>
	<div>


    <el-row :gutter="24" style="margin-top:15px;">
        <el-col :span="10" v-if="data_attach.status=='WorkJob'" >
              <el-popconfirm @onConfirm="fun_attsave" title="确认已经完成所有账单解析并检查无误?">  <el-button style="margin-left:10px;" slot="reference" icon="el-icon-check" type="success" size="small">提交保存 </el-button>  </el-popconfirm>

          <el-tooltip style="margin-left:10px;" content="如果一个文件多个账单则新建" ><el-button @click="fun_billadd" icon="el-icon-plus" type="primary" size="small">新建账单 </el-button> </el-tooltip>
       <el-popconfirm @onConfirm="fun_attcancel" title="确定要忽略此附件账单解析完结任务?">  <el-button style="margin-left:10px;" slot="reference" icon="el-icon-close" type="info" size="small">忽略 </el-button>  </el-popconfirm>

     </el-col>
          <el-col :span="10" v-if="data_attach.status=='CheckJob'" >
              <el-popconfirm @onConfirm="fun_attcheck" title="确认已经检查所有账单无误并提交审核?">  <el-button style="margin-left:10px;" slot="reference" icon="el-icon-check" type="success" size="small">提交审核 </el-button>  </el-popconfirm>
          <el-tooltip style="margin-left:10px;" content="如果一个文件多个账单则新建" ><el-button @click="fun_billadd" icon="el-icon-plus" type="primary" size="small">新建账单 </el-button> </el-tooltip>
        </el-col>
    </el-row>
   <div class="bill_cls" v-for="(billitem,index) in data_attach.billRecordList" :key="index" >
          <el-row :gutter="24">
            <el-form  label-width="100px">

                    <el-tooltip  content="将此账单复制成一个新的账单" ><el-button @click="fun_billcopy(billitem.tableid)" size="small" icon="el-icon-copy-document" type="primary" circle></el-button> </el-tooltip>
                  <el-tooltip style="margin-left:20px;" content="删除当前账单">
                  <el-popconfirm @onConfirm="fun_billdel(billitem.tableid)" title="确定要删除?"><el-button type="danger"  size="small" icon="el-icon-delete"  slot="reference" circle></el-button>
                  </el-popconfirm> </el-tooltip>

                  </el-col>
            </el-form>
          </el-row>


  <vxe-table   border  show-overflow  show-footer :ref="'xTable'+billitem.tableid"
          :data="billitem.billRecordDetailList"
          :mouse-config="{selected: true}" :edit-rules="data_datacheck" :footer-method="footerMethod" :footer-cell-class-name="footerCellClassName"
          :checkbox-config="{range: true}" :keyboard-config="{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true,enterToTab:true, editMethod:(config)=>editMethod(config,'xTable'+billitem.tableid)}"
          :edit-config="{showStatus: true,trigger: 'dblclick', mode: 'cell'}"  @keydown="fun_tablekeydown({$event},billitem.tableid)">
            <vxe-column  field="costName" width="180" title="原始费用名称"></vxe-column>
             <vxe-column field="myshippingSysCode" width="180" title="费用名称" :edit-render="{name: '$select',options:dict_fee}"></vxe-column>
          <vxe-column field="feeStandard" title="标准" width="100" :edit-render="{name: '$select',options:dict_feestandard}"></vxe-column>
          <vxe-column field="unitPrice" title="单价" width="160" :edit-render="{name: '$input',props: {type: 'number'}}"></vxe-column>
          <vxe-column field="quantity" title="数量" width="100" :edit-render="{name: '$input',props: {type: 'number'}}"></vxe-column>
          <vxe-column field="amount" title="金额" width="160" :edit-render="{name: '$input',props: {type: 'number'}}"></vxe-column>
            <vxe-column field="currency" title="币别" width="100" :edit-render="{name: '$select',options:dict_currency}"></vxe-column>
          <vxe-column field="exchangeRate" title="汇率" width="100" :edit-render="{name: '$input'}"></vxe-column>
          <vxe-column field="remark" title="备注" :edit-render="{name: '$input'}"></vxe-column>
         <vxe-column v-if="data_attach.status=='WorkJob'||data_attach.status=='CheckJob'" :span="1" width="60" >
            <template #default="{row}">
              <vxe-button status="danger" size="small" @click="fun_billdetailrow_del(billitem.tableid,row)" icon="el-icon-delete" circle></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>

              </div>

   </div>


</template>

<script>

	export default{
		data(){
			return{
				workgid:"",
				workdata:{},
        data_attach:{},
        activeNames:[1,2,3],
        billaddinit: {payingFor:null, bookingBill:null,  portOfLoading:null, unloadingPort:null, sailingDate:null,totalrmb:0,totalusd:0,billRecordDetailList:[] },
        billDecailinit:{id:0,myshippingSysName:null,feeStandard:null,unitPrice:0,quantity:1,amount:0,currency:null,exchangeRate:null,remark:null}
        ,dict_currency:[],
        dict_fee:[],
        dict_feestandard:[],
        dict_settlefor:[],
        data_datacheck:{//表格数据校验
            unitPrice:[ {type:'number',message:'必须是数值！'} ],
            quantity:[{type:'number',message:'必须是数值！'}]
        }

			}
		},
		mounted(){

			if(this.$route.query.workgid)
			{
				this.workgid=this.$route.query.workgid
				getworkgid(this.workgid).then((res)=>{
					this.workdata=res.data;
        getattach(res.data.dataGId).then(arrs=>{
             this.data_attach=arrs.data;

             for(let i=0;i<this.data_attach.billRecordList.length;i++)
            {
              this.data_attach.billRecordList[i].tableid=i;
                for(let id=0;id<this.data_attach.billRecordList[i].billRecordDetailList.length;id++){
                  this.data_attach.billRecordList[i].billRecordDetailList[id].id=id
                }
            }
            if(this.data_attach.billRecordList==null||this.data_attach.billRecordList.length==0)
            {
              this.fun_billadd();
            }

        })

          getdict("currency").then(res=>{//币种
          res.data.forEach(item => {
            item.label=item.value+" "+item.title
          });
          this.dict_currency=res.data;
          })

           getdict("fee").then(res=>{//费用名称
               res.data.forEach(item => {
            item.label=item.title
          });
          this.dict_fee=res.data;
          })

           getdict("feestandard").then(res=>{//费用标准
               res.data.forEach(item => {
            item.label=item.title
          });
          this.dict_feestandard=res.data;
          })

           getdict("settlefor").then(res=>{//付费对象
               res.data.forEach(item => {
            item.label=item.title
          });
          this.dict_settlefor=res.data;
          })

				})
			}else{
        this.$thisapp.msg('Id丢失',0)
        return
      }
		},
		methods:{fun_getbilltotal(){
         let rmbtotal=0;
         let usdtotal=0;
            for(let bill of this.data_attach.billRecordList)
            {
              for(let item of bill.billRecordDetailList){

                if(item.currency=="RMB")
                            {rmbtotal+=Number(item.amount)}
                            if(item.currency=="USD")
                            {usdtotal+=Number(item.amount)}
              }
            }
                    return "RMB:"+rmbtotal+"   USD:"+usdtotal
        },
      editMethod({row,column},refid){
            let talbe = this.$refs[refid]
              // 重写默认的覆盖式，改为追加式
              talbe[0].setActiveCell(row, column)
        },
        footerMethod ({columns, data })
        {
              return[
                columns.map((column,columnIndex)=>{
                  if(columnIndex==2||columnIndex==3){
                    data.forEach(item=>{
                      if(item.unitPrice&&item.quantity)
                      {
                      item.amount=(item.unitPrice*item.quantity).toFixed(2)
                      }
                    })

                  }

                       if (['quantity'].includes(column.property)) {
                          return "合计:";
                       }
                     if (['amount'].includes(column.property)) {
                    var rmbtotal=0,usdtotal=0;
                    data.forEach(item=>{
                      if(item){
                            if(item.currency=="RMB")
                            {rmbtotal+=Number(item.amount)}
                            if(item.currency=="USD")
                            {usdtotal+=Number(item.amount)}

                        }
                    });
                    return "RMB:"+rmbtotal+" \r\n  USD:"+usdtotal
                  }

                })
              ]
        },
          footerCellClassName ({ $rowIndex, columnIndex }) {
              if (columnIndex === 3) {
                if ($rowIndex === 0) {
                  return 'cls_total'
                }
              }

            },

      fun_billadd(){//账单增加

      let bill=this.$ysapp.copyobj(this.billaddinit)
        bill.billRecordDetailList.push()
        bill.tableid=this.data_attach.billRecordList.length
        this.data_attach.billRecordList.push(bill)
        this.fun_billddetail_add(bill.tableid)
      },
      fun_billcopy(tableid){
        let bill=this.$ysapp.copyobj( this.data_attach.billRecordList.filter(item=>item.tableid==tableid)[0])
            bill.tableid=this.data_attach.billRecordList.length
            bill.gid=null
            this.data_attach.billRecordList.push(bill)
      },
          fun_attsave(){
            //提交保存
             this.fun_attdataformat()
            attachsave(this.data_attach).then(res=>{
               this.data_attach.status="Ok";
               this.fun_workupstatus(100)
               this.$thisapp.msg('保存成功！');
            })

          },
          //附件数据格式化
          fun_attdataformat(){

              this.data_attach.billRecordList.forEach(bill=>{
                bill.billRecordDetailList.forEach(detial=>{
                 let fl= this.dict_fee.filter(item=>item.value==detial.myshippingSysCode);

                 if(fl&&fl.length>0){

                   detial.myshippingSysName=fl[0].title
                 }
                })
              })

              return true
          }
          ,
            fun_attcheck(){
            //提交审核
            this.fun_attdataformat()
            attachcheck(this.data_attach).then(res=>{
               this.data_attach.status="Ok";
                this.fun_workupstatus(100)
               this.$thisapp.msg('审核成功！');

            })

          },
          fun_attcancel(){//忽略取消此任务
              attachupstatus({Gid:this.data_attach.gid,status:'Cancel'}).then(res=>{
                 this.data_attach.status="Cancel";
                  this.fun_workupstatus(101)
                   this.$thisapp.msg('操作成功！');
              })

          }
          ,
          //移除账单
          fun_billdel(tableid)
          {
              let getlist=this.data_attach.billRecordList.filter(item=>item.tableid!=tableid);
              for (let index = 0; index < getlist.length; index++) {
               getlist[index].tableid=index
              }
              this.data_attach.billRecordList=this.$ysapp.copyobj(getlist);
              this.$thisapp.msg('删除成功')
          },
          fun_billdetailrow_del(billid,data)
          {//订单中移除明细

                  let billdlist=this.data_attach.billRecordList[billid].billRecordDetailList;
                  let newlist=billdlist.filter(item=>item.id!=data.id)
                    for(let ii=0;ii<newlist.length;ii++){
                      newlist.id=ii
                    }
                    this.data_attach.billRecordList[billid].billRecordDetailList=newlist
          },
          fun_billddetail_add(billid)
          {//订单中追加一个明细
              let _addc=this.$ysapp.copyobj(this.billDecailinit);

              let billdlist=this.data_attach.billRecordList[billid].billRecordDetailList;
               _addc.id=billdlist.length
             billdlist.push(_addc)

          },
          fun_tablekeydown(eve,billtableid)
          {

            let keycode=eve.$event.$event.keyCode;
            if(keycode==40)
            {
              let rowid= eve.$event.$table.getSelectedCell().row.id
              let bill=this.data_attach.billRecordList.filter(item=>item.tableid==billtableid)[0]

              if(rowid==bill.billRecordDetailList.length-1){
                this.fun_billddetail_add(billtableid)
              }
            }
          },
          fun_dictget(dictlist,value)
          {
            var dl=dictlist.filter(item=>item.value==value)
            if(dl&&dl.length>0)
            { return dl[0] }
            else{dl= {key:value,title:value,value:value,label:value} }
            return dl
          },
          fun_workupstatus(status){//修改任务状态
            let gid=this.workdata.gid
            	upstatus(gid, status).then((res) => {});
          },
          fun_inset(data)
          {
            console.log(data)
          }
		}
	}


</script>

<style>
#app{
  width: 99%;
}
.el-input__inner{
  height:34px;
  line-height: 34px;
}
.bill_cls{
  padding:15px 0px;
  border-bottom: 2px dashed #e8eaec;
}
.bill_cls:last-child{
  border-bottom: none;
}
.cls_total{
  font-size: 16px;
  color: #409EFF;
  font-weight: 900;
  text-align:right;
}
/*失败原因 */
.failure-reason{
  margin-top: 5px;
}
.failure-reason div{
  color: #f45e5e;
  font-size: 14px;
}
.failure-reason .el-icon-warning{
  margin-right: 5px;
}
.file-download a span.el-link--inner{
  border: none !important;
  padding-right: 0px;
}
.information-list{
  margin-top: 3px;
}
.information-list span{
  border-right: 2px solid #d8d8d8;
  padding-right:10px;
  border-radius: 2px;
}
.information-list span b{
  color: #858585;
  font-weight: normal;
}
.vxe-header--column .vxe-cell--edit-icon, .vxe-header--column .vxe-cell-help-icon{
  margin-top: -4px;
}
.vxe-table--header thead tr th:first-child,.vxe-table--body tbody tr td:first-child{
  padding-left:10px !important;
}
</style>
